import React, { useState, useEffect } from 'react';
import {
    Box,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    Paper,
    Button,
    Typography,
    Select,
    MenuItem,
    FormControl,
    InputLabel,
    Pagination,
    Snackbar,
    Alert,
    CircularProgress
} from '@mui/material';
import { getUserPermissions, updateUserPermission, UserPermission } from '../../api/permission';
import './Permission.css';

// 权限选项
const permissionOptions = [
    { access_id: '1', access_name: 'Admin', label: '管理员' },
    { access_id: '2', access_name: 'Advisor', label: '顾问' },
    { access_id: '3', access_name: 'User', label: '用户' }
];

const Permission: React.FC = () => {
    // 用户权限列表
    const [permissions, setPermissions] = useState<UserPermission[]>([]);

    // 加载状态
    const [loading, setLoading] = useState<boolean>(false);

    // 错误信息
    const [error, setError] = useState<string | null>(null);

    // 分页信息
    const [page, setPage] = useState<number>(1);
    const [limit] = useState<number>(10);
    const [total, setTotal] = useState<number>(0);

    // 提示信息
    const [snackbarOpen, setSnackbarOpen] = useState<boolean>(false);
    const [snackbarMessage, setSnackbarMessage] = useState<string>('');
    const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error' | 'info' | 'warning'>('info');

    // 获取用户权限列表
    const fetchPermissions = async () => {
        setLoading(true);
        setError(null);

        try {
            // 获取当前登录用户ID，这里假设从localStorage中获取
            const uid = localStorage.getItem('uid') || '1';

            const response = await getUserPermissions({
                uid,
                page: page.toString(),
                limit: limit.toString()
            });

            setPermissions(response.detail || []);
            setTotal(response.total || 0);
        } catch (error) {
            console.error('获取用户权限列表失败:', error);
            setError('获取用户权限列表失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    // 页面加载时获取用户权限列表
    useEffect(() => {
        fetchPermissions();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // 处理权限变更
    const handlePermissionChange = (userId: string, value: string) => {
        const updatedPermissions = permissions.map((permission) => {
            if (permission.user_id === userId) {
                // 根据access_id查找对应的access_name
                const selectedOption = permissionOptions.find((option) => option.access_id === value);
                return {
                    ...permission,
                    access_id: value,
                    access_name: selectedOption ? selectedOption.access_name : permission.access_name
                };
            }
            return permission;
        });

        setPermissions(updatedPermissions);
    };

    // 处理提交
    const handleSubmit = async (userId: string) => {
        try {
            // 获取当前登录用户ID
            const uid = localStorage.getItem('uid') || '1';

            // 获取要更新的权限信息
            const permission = permissions.find((p) => p.user_id === userId);

            if (!permission) {
                throw new Error('未找到要更新的权限信息');
            }

            // 调用API提交权限变更
            await updateUserPermission({
                uid,
                user_id: permission.user_id,
                access_id: permission.access_id,
                access_name: permission.access_name
            });

            setSnackbarMessage('权限更新成功');
            setSnackbarSeverity('success');
            setSnackbarOpen(true);

            // 重新获取权限列表
            await fetchPermissions();
        } catch (error) {
            console.error('更新权限失败:', error);
            setSnackbarMessage('权限更新失败，请稍后重试');
            setSnackbarSeverity('error');
            setSnackbarOpen(true);
        }
    };

    // 处理分页变化
    const handlePageChange = (_event: React.ChangeEvent<unknown>, value: number) => {
        setPage(value);
        // 切换页面后重新获取数据
        fetchPermissions();
    };

    // 关闭提示信息
    const handleSnackbarClose = () => {
        setSnackbarOpen(false);
    };

    return (
        <Box className="permission-page" sx={{ p: 3 }}>
            <Typography variant="h5" component="h1" gutterBottom>
                权限管理
            </Typography>

            {loading && (
                <Box sx={{ display: 'flex', justifyContent: 'center', my: 4 }}>
                    <CircularProgress />
                </Box>
            )}

            {error && (
                <Alert severity="error" sx={{ mb: 2 }}>
                    {error}
                </Alert>
            )}

            {!loading && !error && (
                <>
                    <TableContainer component={Paper} sx={{ mb: 3, borderRadius: '8px', overflow: 'hidden' }}>
                        <Table>
                            <TableHead sx={{ background: '#754fa0' }}>
                                <TableRow>
                                    <TableCell sx={{ fontWeight: 'bold', width: '30%', padding: '16px 24px' }}>
                                        用户名
                                    </TableCell>
                                    <TableCell sx={{ fontWeight: 'bold', width: '40%', padding: '16px 24px' }}>
                                        权限
                                    </TableCell>
                                    <TableCell sx={{ fontWeight: 'bold', width: '30%', padding: '16px 24px' }}>
                                        备注
                                    </TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {permissions.map((permission) => (
                                    <TableRow key={permission.user_id} hover>
                                        <TableCell sx={{ padding: '16px 24px' }}>{permission.user_name}</TableCell>
                                        <TableCell sx={{ padding: '16px 24px' }}>
                                            <Box sx={{ display: 'flex', alignItems: 'center' }}>
                                                <FormControl fullWidth size="small">
                                                    <InputLabel id={`permission-label-${permission.user_id}`}>
                                                        修改权限
                                                    </InputLabel>
                                                    <Select
                                                        labelId={`permission-label-${permission.user_id}`}
                                                        value={permission.access_id}
                                                        label="修改权限"
                                                        onChange={(e) =>
                                                            handlePermissionChange(permission.user_id, e.target.value)
                                                        }>
                                                        {permissionOptions.map((option) => (
                                                            <MenuItem key={option.access_id} value={option.access_id}>
                                                                {option.label}
                                                            </MenuItem>
                                                        ))}
                                                    </Select>
                                                </FormControl>
                                            </Box>
                                        </TableCell>
                                        <TableCell sx={{ padding: '16px 24px' }}>
                                            <Button
                                                variant="contained"
                                                color="primary"
                                                onClick={() => handleSubmit(permission.user_id)}
                                                sx={{
                                                    backgroundColor: '#e3f2fd',
                                                    color: '#fff',
                                                    '&:hover': {
                                                        backgroundColor: '#bbdefb'
                                                    },
                                                    borderRadius: '20px',
                                                    padding: '6px 20px',
                                                    textTransform: 'none',
                                                    fontWeight: 500
                                                }}>
                                                提交
                                            </Button>
                                        </TableCell>
                                    </TableRow>
                                ))}

                                {permissions.length === 0 && (
                                    <TableRow>
                                        <TableCell colSpan={3} align="center" sx={{ padding: '24px' }}>
                                            <Typography color="textSecondary">暂无数据</Typography>
                                        </TableCell>
                                    </TableRow>
                                )}
                            </TableBody>
                        </Table>
                    </TableContainer>

                    <Box sx={{ display: 'flex', justifyContent: 'center', mt: 3 }}>
                        <Pagination
                            count={Math.ceil(total / limit)}
                            page={page}
                            onChange={handlePageChange}
                            color="primary"
                            showFirstButton
                            showLastButton
                        />
                    </Box>
                </>
            )}

            <Snackbar
                open={snackbarOpen}
                autoHideDuration={6000}
                onClose={handleSnackbarClose}
                anchorOrigin={{ vertical: 'top', horizontal: 'center' }}>
                <Alert onClose={handleSnackbarClose} severity={snackbarSeverity} sx={{ width: '100%' }}>
                    {snackbarMessage}
                </Alert>
            </Snackbar>
        </Box>
    );
};

export default Permission;
